package com.ruoyi.sts.service.impl;

import java.io.StringReader;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.sts.domain.EventNotificationAlert;
import com.ruoyi.system.domain.SysMsg;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysMsgService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.ruoyi.sts.mapper.StsDeviceMapper;
import com.ruoyi.sts.domain.StsDevice;
import com.ruoyi.sts.service.IStsDeviceService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

/**
 * 设备Service业务层处理
 * 
 * @author maoxiaodong
 * @date 2025-04-24
 */
@Service
public class StsDeviceServiceImpl implements IStsDeviceService
{
    @Autowired
    private StsDeviceMapper stsDeviceMapper;

    @Autowired
    private ISysMsgService sysMsgService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public StsDevice selectStsDeviceById(Long id)
    {
        return stsDeviceMapper.selectStsDeviceById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param stsDevice 设备
     * @return 设备
     */
    @Override
    public List<StsDevice> selectStsDeviceList(StsDevice stsDevice)
    {
        return stsDeviceMapper.selectStsDeviceList(stsDevice);
    }

    /**
     * 新增设备
     * 
     * @param stsDevice 设备
     * @return 结果
     */
    @Override
    public int insertStsDevice(StsDevice stsDevice)
    {
        stsDevice.setCreateTime(DateUtils.getNowDate());
        return stsDeviceMapper.insertStsDevice(stsDevice);
    }

    /**
     * 修改设备
     * 
     * @param stsDevice 设备
     * @return 结果
     */
    @Override
    public int updateStsDevice(StsDevice stsDevice)
    {
        stsDevice.setUpdateTime(DateUtils.getNowDate());
        return stsDeviceMapper.updateStsDevice(stsDevice);
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteStsDeviceByIds(String ids)
    {
        return stsDeviceMapper.deleteStsDeviceByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteStsDeviceById(Long id)
    {
        return stsDeviceMapper.deleteStsDeviceById(id);
    }

    @Override
    public StsDevice selectStsDeviceByIdCode(String idCode) {
        return stsDeviceMapper.selectStsDeviceByIdCode(idCode);
    }

    @Override
    public StsDevice selectStsDeviceByDeptId3(Long deptId3) {
        return stsDeviceMapper.selectStsDeviceByDeptId3(deptId3);
    }

    /**
     * 修改设备
     *
     * @param xml 设备通知
     * @return 结果
     */
    @Async
    @Transactional
    @Override
    public void updateLastSendTime(String xml)
    {
        try {
            JAXBContext context = JAXBContext.newInstance(EventNotificationAlert.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            String regex = "\\sxmlns=\"[^\"]+\"\\s*";
            xml = xml.replaceAll(regex, "");
            EventNotificationAlert eventNotificationAlert = (EventNotificationAlert)unmarshaller.unmarshal(new StringReader(xml));
            StsDevice stsDevice = stsDeviceMapper.selectStsDeviceByIdCode(eventNotificationAlert.getMacAddress());
            stsDevice.setLastSendTime(new Date());
            String lastSendTime = stsDevice.getLastSendTime() == null?"新接入设备":DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", stsDevice.getLastSendTime());
            if("1".equals(stsDevice.getStatus())){
                List<SysUser> sysUsers = sysUserService.selectDeptAdmin(stsDevice.getDeptId1());
                for(SysUser sysUser: sysUsers){
                    stsDevice.setStatus("0");
                    SysMsg sysMsg = new SysMsg();
                    sysMsg.setType("2");
                    sysMsg.setTitle(String.format("%s 设备上线了,识别码:%s", stsDevice.getName(), stsDevice.getIdCode()));
                    sysMsg.setContent(String.format("场所：%s，设备：%s，识别码：%s，该设备在%s已上线，上一次上传时间在：%s",
                            stsDevice.getDeptName2(), stsDevice.getName(), stsDevice.getIdCode(), DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"),
                            lastSendTime
                    ));
                    sysMsg.setStatus("0");
                    sysMsg.setSendTime(new Date());
                    sysMsg.setSenderId(1L);
                    sysMsg.setReceiverId(sysUser.getUserId());
                    sysMsgService.insertSysMsg(sysMsg);
                }

                SysMsg sysMsg = new SysMsg();
                sysMsg.setType("2");
                sysMsg.setTitle(String.format("%s 设备上线了,识别码:%s", stsDevice.getName(), stsDevice.getIdCode()));
                sysMsg.setContent(String.format("场所：%s，设备：%s，识别码：%s，该设备在%s已上线，上一次上传时间在：%s",
                        stsDevice.getDeptName2(), stsDevice.getName(), stsDevice.getIdCode(), DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"),
                        lastSendTime
                ));
                sysMsg.setStatus("0");
                sysMsg.setSendTime(new Date());
                sysMsg.setSenderId(1L);
                sysMsg.setReceiverId(1L);
                sysMsgService.insertSysMsg(sysMsg);

            }
            stsDeviceMapper.updateLastSendTimeByIdCode(stsDevice);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<StsDevice> selectStsDeviceByLastSendTime() {
        return stsDeviceMapper.selectStsDeviceByLastSendTime();
    }

    @Async
    @Override
    public void updateDeptName(Integer deptLevel, Long deptId, String deptName) {
        stsDeviceMapper.updateDeptName(deptLevel, deptId,deptName);
    }
}
